<?php
namespace TennisTournament\Controller;

use TennisTournament\Form\PlayerForm;
use TennisTournament\Model\Player;
use TennisTournament\Service\PlayerService;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Json\Json;

class PlayerController extends AbstractActionController {

    /** @var PlayerService */
    protected $playerService;

    public function __construct(PlayerService $playerService) {
        $this->playerService = $playerService;
    }

    public function addAction() {
        $playerForm = new PlayerForm();
        $playerForm->get('submit')->setValue('Add');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = array_merge_recursive(
                $request->getPost()->toArray(),
                $request->getFiles()->toArray()
            );
            $playerForm->getInputFilter();
            $playerForm->setData($post);
            if ($playerForm->isValid()) {

                $data = $playerForm->getData();
                $pictureFile = null;
                if (isset($data['pathToPicture']) && is_array($data['pathToPicture'])) {
                    $pictureFile = $data['pathToPicture'];
                }
                $data['pathToPicture'] = "";
                $player = (new Player())->exchangeArray($data);
                if ( $pictureFile != null && is_array($pictureFile)) {
                    $pathToPicture = $this->playerService->uploadPlayerPicture($pictureFile, $player->getName());
                }

                $player->setPathToPicture($pathToPicture);
                $this->playerService->save($player);
            }
        }

        return $this->redirect()->toRoute('management');
    }

    public function showAllAction() {
        $parameters = array();

        $parameters['playersJSON'] = $this->generateJSONArrayFromPlayers();

        return $parameters;
    }

    private function generateJSONArrayFromPlayers() {
        $collectionPlayers = $this->playerService->listAll();
        $collectionPlayersJSON = array();

        /** @var $player Player */
        foreach ($collectionPlayers as $player) {
            array_push($collectionPlayersJSON, $player->toArray());
        }

        return Json::encode($collectionPlayersJSON);
    }

}